#!/bin/bash

WORK_DIR=$(cd $(dirname $0); pwd)

export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:${WORK_DIR}/cartographer/install/lib

source /opt/ros/humble/setup.bash

source ${WORK_DIR}/cartographer_ros/install/setup.bash

debug=0
project=$1
remove=$2

if [ "${project}" == "lib" ]; then
    cd ${WORK_DIR}/cartographer
    mkdir -p ${WORK_DIR}/cartographer/build
    if [ "${remove}" == "1" ]; then
        rm -rf ./build/*
        rm -rf ./install/*
    fi
    cd ${WORK_DIR}/cartographer/build 
    if [ "${debug}" == "1" ]; then
        cmake -DCMAKE_BUILD_TYPE=Debug -DFORCE_DEBUG_BUILD=True -DCMAKE_INSTALL_PREFIX=${WORK_DIR}/cartographer/install .. -G Ninja
    else
        cmake -DCMAKE_INSTALL_PREFIX=${WORK_DIR}/cartographer/install .. -G Ninja
    fi
    ninja
    ninja install
elif [ "${project}" == "ros" ]; then
    cd ${WORK_DIR}/cartographer_ros

    rm -rf ./log/*
    if [ "${remove}" == "1" ]; then
        rm -rf ./build/*
        rm -rf ./install/*
        if [ "${debug}" == "1" ]; then
            colcon build --merge-install --parallel-workers 8 --cmake-args '-DCMAKE_BUILD_TYPE=RelWithDebInfo'
        else
            colcon build --merge-install --parallel-workers 8 
        fi
    else
        if [ "${debug}" == "1" ]; then
            colcon build --merge-install --parallel-workers 8 --cmake-args '-DCMAKE_BUILD_TYPE=RelWithDebInfo' --packages-select cartographer_ros
        else 
            colcon build --merge-install --parallel-workers 8 --packages-select cartographer_ros
        fi
    fi
fi
